/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.multicontext.hibernate;

import io.iec.edp.caf.multicontext.context.PlatformApplicationContext;
import io.iec.edp.caf.multicontext.factory.PlatformBeanFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.domain.EntityScanPackages;
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;
import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.lookup.SingleDataSourceLookup;
import org.springframework.orm.jpa.persistenceunit.PersistenceUnitManager;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.util.List;

/**
 * 注册自定义的Customizer和PersistenceUnitManager
 */
@Configuration
@AutoConfigureBefore(JpaBaseConfiguration.class)
@ConditionalOnProperty(name = "parallel.startup", havingValue = "true")
public class HibernateAutoConfiguration implements BeanFactoryAware, ApplicationContextAware {

    private final DataSource dataSource;

    private final JpaProperties properties;

    private PlatformBeanFactory beanFactory;

    private PlatformApplicationContext applicationContext;

    protected HibernateAutoConfiguration(DataSource dataSource, JpaProperties properties) {
        this.dataSource = dataSource;
        this.properties = properties;
    }

    @Bean
    public PersistenceUnitManager customPersistenceUnitManager() {
        CustomPersistenceUnitManager persistenceUnitManager = new CustomPersistenceUnitManager(applicationContext.getModuleManager());
        persistenceUnitManager.setDataSourceLookup(new SingleDataSourceLookup(this.dataSource));
        persistenceUnitManager.setDefaultDataSource(this.dataSource);
        persistenceUnitManager.setPackagesToScan(getPackagesToScan());
        persistenceUnitManager.setMappingResources(getMappingResources());
        return persistenceUnitManager;
    }

    @Bean
    public HibernatePropertiesCustomizer hibernateCustomizer() {
        return new CustomHibernatePropertiesCustomizer();
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = (PlatformBeanFactory) beanFactory;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = (PlatformApplicationContext) applicationContext;
    }

    protected String[] getPackagesToScan() {
        List<String> packages = EntityScanPackages.get(this.beanFactory).getPackageNames();
        if (packages.isEmpty() && AutoConfigurationPackages.has(this.beanFactory)) {
            packages = AutoConfigurationPackages.get(this.beanFactory);
        }
        return StringUtils.toStringArray(packages);
    }

    private String[] getMappingResources() {
        List<String> mappingResources = this.properties.getMappingResources();
        return (!ObjectUtils.isEmpty(mappingResources) ? StringUtils.toStringArray(mappingResources) : null);
    }
}
